// 个人名片主页，不依赖参数。 需要把名片访客页也改成本页面。
const app = getApp();
const _util = require('./util.js');
const { skeletonData } = require('./card-preview-skeleton-data.js');
const { module, uniacid, appJson, tabbar_type } = app.siteInfo;

Page({
  _privateData: {
    days: '',
    isUnloaded: false,
  },
  data: {
    existCard: {},
    defaultAvatar: './img/default-avatar.png',
    qrShow: false,
    xcxCodeShow: false,
    toggleMore: true,
    shareModalVisible: false,
    appJson: appJson,
    tabbar_type: tabbar_type,
    uniacid: uniacid,
    availablePeriods: [],
    availablePeriodStart: '09:00',
    availablePeriodEnd: '23:00',
    showPeriod: false, // 时间设置暂时先隐藏
    showPeriodAdd: false,
    repeatDays: [
      { name: 0, value: '周日' },
      { name: 1, value: '周一' },
      { name: 2, value: '周二' },
      { name: 3, value: '周三' },
      { name: 4, value: '周四' },
      { name: 5, value: '周五' },
      { name: 6, value: '周六' },
    ],
    recommendGoods: [],
    multiIndex: [0, 0],
    audioStatusLabel: '就绪',
    showHomeBtn: true,
    isShowBadge:false,
    isWXWork: app.isWXWork,
    labelAlias: {},
    showExtra: module !== 'ws_training_education' && module.indexOf('ws_micro_shop') === -1,
    skeletonData,
    isData: false
  },

  onLoad: function () {
    let showHomeBtn = _util.shouldShowFixedMenu('common/component/universal-card/card-preview');
    showHomeBtn && this.findActualHome();
    showHomeBtn && this.setData({
      'floatItems[0].show': true,
    });
    this.getLiveScreen();
    this.__innerAudioContext = wx.createInnerAudioContext();
    this.getLabelAlias();
  },

  onShow: function () {
    // TODO, 转发退出或成功，本生命周期还会执行
    let that = this;
    let openid = wx.getStorageSync('OPENID') || wx.getStorageSync('openid');
    this.setData({
      isEmptyCard: false,
    });

    if (!openid) {
      if (module === 'ws_micro_shop') {
        app.ws_micro_shoplogin().then(function () {
          openid = wx.getStorageSync('OPENID');
          that.setData({ openid });
          that.getCardDetail(openid);
        });
      } else {
        app.util._wxLogin().then(res => {
          openid = res.openid || res.data.data.openid;
          that.setData({ openid });
          that.getCardDetail(openid);
        });
      }
    } else {
      this.setData({ openid });
      this.getCardDetail(openid);
    }
    // 兼容modal分享弹框
    !this.shareModalVisible && wx.showTabBar({});
  },

  onHide() {
    this.__innerAudioContext.src && this.audioStop();
  },

  onUnload() {
    this.__innerAudioContext.src && this.audioStop();
    this.__innerAudioContext.destroy();
    // TODO，onshow生命周期的异步操作函数都要暂停！
    this._privateData.isUnloaded = true;
  },

  getLabelAlias() {
    app.util.request({
      url: 'card/api/aliasList',
      showLoading: true,
      success: res => {
        if (res.data && res.data.errno === 0) {
          const data = res.data.data;
          this.setData({ labelAlias: data });
        }
      },
    });
  },

  // 获取名片详细信息
  getCardDetail(openid) {
    let that = this;
    let qr_path = 'common/component/universal-card/card-show';

    app.util.request({
      url: 'card/api/get_card_detail',
      data: { openid, qr_path },
      showLoading: true,
      success: function (res) {
        if (Number(res.data.errno) === 0) {
          let existCard = res.data.data;
          existCard.images = (existCard.images || []).filter(v => v);
          that.setData({
            existCard,
          }, () => {
            that.audioContext();
            that.createAnimation(existCard.audioDuration);
            that.getMessageTip(openid)
          });
          if (Number(existCard.ur_msg) > 0 && !app.isCheckedCardMsg) {
            wx.showModal({
              title: '提示',
              content: `你有${existCard.ur_msg}条未读消息`,
              success: function (res) {
                app.isCheckedCardMsg = true;
                if (res.confirm) {
                  that.gotoMsg();
                } else if (res.cancel) {
                  // console.log('用户点击取消');
                }
              },
            });
          }
          wx.setStorageSync('masterInfo', existCard);  // 留言页面用到
          app.util.request({
            url: 'card/api/get_member_record',
            data: {
              openid,
              op: '1',
              page: '1',
              pagesize: '10',
              cardid: existCard.id,
            },
            showLoading: true,
            success: function (res) {
              if (res.data.errno === 0) {
                const guests = res.data.data.list;
                const guestsCount = Number(res.data.data.total) || 0;
                that.setData({
                  guests: guests.slice(0, 5),
                  guestsCount,
                });
              }
            },
          });
          // 获取在线时间段
          app.util.request({
            url: 'card/api/get_service_time',
            data: {
              card_id: existCard.id,
            },
            showLoading: true,
            success: res => {
              // 处理availablePeriods.day;
              let periods = res.data.data;
              let weekDay = { 1: '一', 2: '二', 3: '三', 4: '四', 5: '五', 6: '六' };
              periods.map(item => {
                if (item.day) item.day = item.day.split(',').map(i => { return '周' + (Number(i) === 0 ? '日' : weekDay[i]) }).join();
                return item;
              });
              that.setData({
                availablePeriods: periods,
              });
            },
          });
          if (!existCard.id) {
            app.util.navigateTo('common/component/universal-card/pages/card-empty',{},true);
            !that._privateData.isUnloaded && that.setData({
              isEmptyCard: true,
            });
            return;
          }
          that.setData({
            isData: true,
          })
        }else {
          that.setData({
            isData: true,
          })
        }
      },
      fail: res => {
        that.setData({
          isData: true,
        })
      }
    });
  },

  // 留言提醒
  getMessageTip(openid) {
    app.util.request({
      url: 'card/record/getMessageTip',
      data: {
        openid,
      },
      success: res => {
        console.log("======getMessageTip=====", res)
        if (res.data.errcode == 0) {
          this.setData({
            isShowBadge: res.data.data ? true : false,
          })
        }
      }
    })
  },

  onShareAppMessage: function (res) {
    const { id, share_title, company, name } = this.data.existCard;
    let path = 'common/component/universal-card/card-show?cardid=' + id;
    if (app.siteInfo.module === 'ws_micro_shop') {
      path = path + '&sid=' + (app.ws_micro_shop_globalData.shopid || 0);
    }

    this.setData({
      shareModalVisible: false,
    });

    return this.data.actionSheetType === 'goods' ? {
      title: this.data.goodsToShare.name,
      path: 'ws_micro_shop/pages/goods/goods?id=' + this.data.goodsToShare.id + '&shopid=' + (app.ws_micro_shop_globalData.shopid || 0),
      webViewUrl: this.data.goodsToShare.cover_pic,
    } : {
      title: share_title || (company ? `您好，我是${company}的${name}，` : '') + '这是我的电子名片，敬请惠存',
      path: _util.spliceSharePath(path, 'share'),
    };
  },

  onUserOpStatistic: function (e) {
    if (e.op === 'share') {
      if (module === 'ws_training_education') {
        const store_id = wx.getStorageSync('store_id');
        app.util.request({
          url: 'entry/wxapp/api',
          data: {
            app: 'consult',
            act: 'taskStatics',
            type: '0',
            store_id,
            consult_openid: this.data.existCard.openid,
          },
        });
      }
    }
  },

  checkLocation(e) {
    const { latitude, longitude, address } = this.data.existCard;
    wx.openLocation({
      latitude: parseFloat(latitude),
      longitude: parseFloat(longitude),
      address,
    });
  },

  gotoHome(e) {
    const homeModule = appJson[0];
    let moduleName = homeModule.module;
    let tpl = app.siteInfo.template_num;
    let url = '';
    if (moduleName === 'ws_micro_company' && tpl) {
      url = moduleName + (tpl === '0' ? '_visual' : '_' + tpl) + '/pages/index/index';
    } else {
      if (homeModule.homePage) {
        url = homeModule.homePage;
      } else if (Number(tabbar_type) === 2 && homeModule.tabBar.v_list) {
        url = homeModule.tabBar.v_list[0].pagePath;
      } else {
        url = homeModule.tabBar.list[0].pagePath;
      }
    }
    app.util.navigateTo(url);
  },

  // 前往编辑页面
  gotoEdit(e) {
    let url = e.currentTarget.dataset.type === 'edit'
      ? 'common/component/universal-card/pages/card-edit?goback=common/component/universal-card/card-preview'
      : 'common/component/universal-card/pages/card-list';
    app.util.navigateTo(url);
  },

  // 前往留言列表
  gotoMsg(e) {
    let openid = this.data.openid;
    let id = this.data.existCard.id;
    let url = 'common/component/universal-card/pages/msg-list?openid=' + openid + '&cardid=' + id;
    app.util.navigateTo(url);
    this.data.isWxWork && _util.requestSubscribeMessage;
  },

  // 查看访客列表
  checkGuests(e) {
    let { id: cardId, issale } = this.data.existCard;
    let url = 'common/component/universal-card/pages/guests-list?cardId=' + cardId + '&issale=' + issale;
    if (app.modules === 'ws_training_education' && wx.getStorageSync('te_userInfo').is_admin === '4') url = 'business/student-management/list/list';
    app.util.navigateTo(url);
    this.data.isWxWork && _util.requestSubscribeMessage();
  },

  // 生成名片缩略图 分享海报
  createThumb(e) {
    let card_id = this.data.existCard.id;
    let openid = this.data.openid;
    let url = 'common/component/universal-card/pages/msg-list?openid=' + openid + '&cardid=' + card_id + '&isCard=1';
    app.util.navigateTo(url);

    return this.setData({
      shareModalVisible: false,
    });
  },

  showMyCode(e) {
    app.util.navigateTo(`common/component/universal-card/pages/msg-list?isPoster=1&openid=${this.data.openid}`);
  },

  closeMyCode(e) {
    this.setData({
      xcxCodeShow: false,
    });
  },

  closeQrShow(e) {
    this.setData({ qrShow: false });
  },

  saveQrShow(e) {
    const url = this.data.qrCode;
    wx.downloadFile({
      url,
      success: function (res) {
        if (res.statusCode === 200) {
          const filePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath,
            success: function (res) {
              wx.showToast({
                title: '保存成功',
              });
            },
          });
        }
      },
    });
  },

  toggleMore(e) {
    this.setData({
      toggleMore: !this.data.toggleMore,
    });
  },

  addWechat(e) {
    let wechatId = this.data.existCard.wechatId || this.data.existCard.mobile || '';
    if (e.currentTarget.dataset.wechatid) wechatId = e.currentTarget.dataset.wechatid;

    wechatId && wx.setClipboardData({
      data: wechatId,
      success: (result) => {
        // body
      },
    });
  },

  addCompany(e) {
    let company = this.data.existCard.company || '';
    if (e.currentTarget.dataset.company) company = e.currentTarget.dataset.company;
    company && wx.setClipboardData({
      data: company,
      success: (result) => {
        // body
      },
    });
  },

  addEmail(e) {
    let email = this.data.existCard.email || '';
    if (e.currentTarget.dataset.email) email = e.currentTarget.dataset.email;
    email && wx.setClipboardData({
      data: email,
      success: (result) => {
        // body
      },
    });
  },

  callMe(e) {
    let phoneNumber = this.data.existCard.mobile;
    if (e.currentTarget.dataset.phone) phoneNumber = e.currentTarget.dataset.phone;

    const exp = app.util.phoneExp.mobile;
    if (phoneNumber && exp.test(phoneNumber)) {
      wx.makePhoneCall({
        phoneNumber,
      });
    } else if (phoneNumber && !exp.test(phoneNumber)) {
      wx.showToast({
        title: '无效的号码',
        icon: 'none',
      });
    } else {
      wx.showToast({
        title: '该用户没留下手机号码',
        icon: 'none',
      });
    }
  },

  showActions(e) {
    let that = this;
    wx.hideTabBar({
      aniamtion: true,
      complete: function() {
        that.setData({
          shareModalVisible: true,
          actionSheetType: 'card',
        });
      },
    });
  },

  shareModalClose(e) {
    this.setData({
      shareModalVisible: false,
    },
    function() {
      wx.showTabBar({
        aniamtion: true,
      });
    });
  },

  bindPeriodStartChange(e) {
    console.log('开始时间', e.detail.value);
    this.setData({
      availablePeriodStart: e.detail.value,
    });
  },

  bindPeriodEndChange(e) {
    this.setData({
      availablePeriodEnd: e.detail.value,
    });
  },

  tooglePeriodAdd(e) {
    this.setData({
      showPeriodAdd: !this.data.showPeriodAdd,
    });
  },

  repeatPeriodChange(e) {
    // console.log(e.detail.value);
    let weekDay = { 1: '一', 2: '二', 3: '三', 4: '四', 5: '五', 6: '六' };
    let daysStr = e.detail.value.map(i => { return '周' + (Number(i) === 0 ? '日' : weekDay[i]) }).join();
    this._privateData.days = e.detail.value;
    this._privateData.daysStr = daysStr;
  },

  addPeriod() {
    if (!this._privateData.days) {
      wx.showToast({
        title: '请选择重复周期',
        icon: 'none',
      });
      return false;
    }

    let tmpLen = this.data.availablePeriods.length;
    let tmpKey = `availablePeriods[${tmpLen}]`;
    app.util.request({
      // 此接口有id值的话就是修改，没有有其他值则是新增
      url: 'card/api/set_service_time',
      data: {
        day: this._privateData.days,
        starttime: this.data.availablePeriodStart,
        endtime: this.data.availablePeriodEnd,
        card_id: this.data.existCard.id,
        status: 1,
      },
      method: 'POST',
      cachetime: 0,
      showLoading: true,
      success: res => {
        this.setData({
          [tmpKey]: {
            day: this._privateData.daysStr,
            starttime: this.data.availablePeriodStart,
            endtime: this.data.availablePeriodEnd,
            status: '1',
          },
        });
      },
      complete: res => {
        this._privateData.days = '';
        this.setData({
          showPeriodAdd: false,
        });
      },
    });
  },

  canclePeriod() {
    this.setData({
      showPeriodAdd: false,
    });
  },

  switchChange(e) {
    console.log(e.detail.value);
    let periodID = e.currentTarget.dataset.periodId;
    periodID && app.util.request({
      // 此接口有id值的话就是修改，没有有其他值则是新增
      url: 'card/api/up_time_status',
      data: {
        id: periodID,
        status: e.detail.value ? 1 : 2,
      },
      method: 'POST',
      cachetime: 0,
      showLoading: true,
      success: res => {
        // donothing;
      },
    });
  },

  /**
   * 显示删除按钮
   */
  showDeleteButton: function (e) {
    let periodIndex = e.currentTarget.dataset.periodindex;
    this.setXmove(periodIndex, -65);
  },

  /**
   * 隐藏删除按钮
   */
  hideDeleteButton: function (e) {
    let periodIndex = e.currentTarget.dataset.periodindex;
    this.setXmove(periodIndex, 0);
  },

  /**
   * 设置movable-view位移
   */
  setXmove: function (periodIndex, xmove) {
    let key = `availablePeriods[${periodIndex}].xmove`;
    this.setData({
      [key]: xmove,
    });
  },

  /**
   * 处理movable-view移动事件
   */
  handleMovableChange: function (e) {
    if (e.detail.source === 'friction') {
      if (e.detail.x < -30) {
        this.showDeleteButton(e);
      } else {
        this.hideDeleteButton(e);
      }
    } else if (e.detail.source === 'out-of-bounds' && e.detail.x === 0) {
      this.hideDeleteButton(e);
    }
  },

  /**
   * 处理touchstart事件
   */
  handleTouchStart(e) {
    this.startX = e.touches[0].pageX;
  },

  /**
   * 处理touchend事件
   */
  handleTouchEnd(e) {
    if (e.changedTouches[0].pageX < this.startX && e.changedTouches[0].pageX - this.startX <= -30) {
      this.showDeleteButton(e);
    } else if (e.changedTouches[0].pageX > this.startX && e.changedTouches[0].pageX - this.startX < 30) {
      this.showDeleteButton(e);
    } else {
      this.hideDeleteButton(e);
    }
  },

  /**
   * 删除产品
   */
  handleDeleteProduct: function ({ currentTarget: { dataset: { periodId, periodindex }}}) {
    let availablePeriods = this.data.availablePeriods;
    availablePeriods.splice(periodindex, 1);

    this.setData({
      availablePeriods,
    });
    app.util.request({
      url: 'card/api/del_service_time',
      data: {
        id: periodId,
      },
      showLoading: true,
      success: function (res) {
        // Number(res.data.errno);
      },
    });
  },

  createAnimation(time) {
    const animationBar = wx.createAnimation({
      duration: time / 2 || 1000,
      timingFunction: 'linear',
    });
    const animationBlock = wx.createAnimation({
      duration: time / 2 || 1000,
      timingFunction: 'linear',
    });
    this.__animationBlock = animationBlock;
    this.__animationBar = animationBar;
  },

  animationAudioplayBar(status) {
    status === 'playing' && this.__animationBar.width(this.data.x).step();
    status === 'stop' && this.__animationBar.width(0).step({ duration: 10 });
    this.setData({ animationBar: this.__animationBar.export() });
  },

  animationAudioplayBlock(status) {
    status === 'playing' && this.__animationBlock.translateX(this.data.x).step();
    status === 'stop' && this.__animationBlock.translateX(0).step({ duration: 10 });
    this.setData({ animationBlock: this.__animationBlock.export() });
  },

  audioContext() {
    this.__innerAudioContext.autoplay = false;
    this.__innerAudioContext.src = this.data.existCard.audio;
    this.__innerAudioContext.onPlay(() => {
      console.log('开始播放');
      this.setData({ audioStatus: 'playing', audioStatusLabel: '播放' });
      this.animationAudioplayBar('playing');
      this.animationAudioplayBlock('playing');
    });
    this.__innerAudioContext.onPause(() => {
      console.log('暂停播放');
      this.setData({ audioStatus: 'pause' });
    });
    this.__innerAudioContext.onStop(() => {
      console.log('停止播放');
      this.setData({ audioStatus: 'stop', audioStatusLabel: '停止' });
      this.animationAudioplayBar('stop');
      this.animationAudioplayBlock('stop');
    });
    this.__innerAudioContext.onEnded(() => {
      console.log('播放结束');
      this.setData({ audioStatus: 'stop', audioStatusLabel: '停止' });
      this.animationAudioplayBar('stop');
      this.animationAudioplayBlock('stop');
    });
  },

  audioPlay() {
    console.log('will play');
    this.__innerAudioContext.play();
  },

  audioPause() {
    console.log('will pause');
    this.__innerAudioContext.pause();
  },

  audioStop() {
    this.__innerAudioContext.stop();
    this.animationAudioplayBar('stop');
    this.animationAudioplayBlock('stop');
  },

  getLiveScreen() {
    wx.getSystemInfo({
      success: res => {
        this.setData({ screenWidth: res.screenWidth, x: (res.screenWidth - 60) * 0.76 * 0.7 });
      },
    });
  },

  previewPicture(e) {
    let { url, urls } = e.currentTarget.dataset;
    wx.previewImage({
      current: url,
      urls,
    });
  },

  doRequest(options, success, fail) {
    app.util.request({
      ...options,
      success: res => {
        res.data.errno === 0 && success(res);
      },
      fail: err => {
        fail && fail(err);
      },
    });
  },

  findActualHome() {
    const homeModule = appJson[0];
    let actualTab;
    if (Number(tabbar_type) === 2 && homeModule.tabBar.v_list) {
      actualTab = homeModule.tabBar.v_list.find(item => item.pagePath === homeModule.homePage) || homeModule.tabBar.v_list[0];
    } else {
      actualTab = homeModule.tabBar.list.find(item => item.pagePath === homeModule.homePage) || homeModule.tabBar.list[0];
    }
    this.setData({ actualTab: actualTab });
  },
  
});
